package au.com.mason.propertyTracker.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import au.com.mason.propertyTracker.domain.Status;
import au.com.mason.propertyTracker.editor.EnumEditor;
import au.com.mason.propertyTracker.form.EditPropertyForm;
import au.com.mason.propertyTracker.service.PropertyService;
import au.com.mason.propertyTracker.service.SuburbService;

@Controller
public class EditProperty {
	
	private PropertyService propertyService;
	private SuburbService suburbService;

	@Autowired
	public EditProperty(PropertyService propertyService, SuburbService suburbService) {
		this.propertyService = propertyService;
		this.suburbService = suburbService;
	}
	
	@RequestMapping("/displayEditProperty.action")
	public String displayEditProperty(HttpSession session, Map model) {
		EditPropertyForm editPropertyForm = new EditPropertyForm();
		int propertyId = (Integer) session.getAttribute("propertyId");
		editPropertyForm.setProperty(propertyService.getProperty(propertyId));
		model.put("suburbs", suburbService.getSuburbs());
		model.put("editPropertyForm", editPropertyForm);
		
		model.put("statuses", Status.values());
		
		return "editProperty";
	}
	
	@RequestMapping("/submitEditProperty.action")
	public String submitEditProperty(EditPropertyForm editPropertyForm) {
		propertyService.updateProperty(editPropertyForm.getProperty());
		
		return "redirect:SubmitFilterPropertiesFromSession.action";
	}
	
	@InitBinder
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
	    DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm");
	    df.setLenient(false);
	    CustomDateEditor editor = new CustomDateEditor(df, false);
	    binder.registerCustomEditor(Date.class, editor);
	    binder.registerCustomEditor(Status.class, new EnumEditor(Status.class));
	}
	
}
